var layer = layui.layer //弹层
    ,table = layui.table //表格
    form = layui.form,$ = layui.jquery,laydate = layui.laydate,cbLists=[], id = getQueryVariable("id");

//主表数据数据
let dataList = [];
//明细数据
let detailList = [];
layer.ready(function () {
    //获取详情信息
    $.ajax({
        url:"receivePayment/getSplitData?id="+id,
        success:function(res){
            if(res.status == 200){
                //主表信息赋值
                if(null != res.data){
                    for(let i in res.data){
                        res.data[i]["tempId"] = GenNonDuplicateID(3) + (i+1);
                        dataList.push(res.data[i]);
                    }
                }
                table.reload('mainstableid',{data : dataList});
                return false;
            }else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
    form.render();

});

table.render({
    elem: '#mains'
    ,data:dataList
    ,cols: [[
        {field:'billNo', title:'收款编号',sort:true,width: 220}
        ,{field:'time', title:'收款日期',sort:true,width: 120}
        ,{field:'customerName', title:'客户名称',sort:true,width: 120}
        ,{field:'currency', title:'币种',sort:true,width: 120}
        ,{field:'rmbRate', title:'人民币汇率',sort:true,width: 120}
        ,{field:'usdRate', title:'美金汇率',sort:true,width: 120}
        ,{field:'entryAmount', title:'入账金额',sort:true,width: 120}
        ,{field:'bankDeductionExcept', title:'银行扣费（外）',sort:true,width: 120}
        ,{field:'bankDeductionCapital', title:'银行扣费（本）',sort:true,width: 120}
        ,{field:'collectionAmount', title:'收汇金额',sort:true,width: 120}
        ,{field:'claimed', title:'已认领金额',sort:true,width: 120}
        ,{field:'splitCompletedAmount', title:'已拆分金额',sort:true,width: 120}
        ,{field:'undividedAmount', title:'未拆分金额',sort:true,width: 120}
        ,{field:'memo', title:'备注',sort:true,width: 120}
    ]]
    ,id: 'mainstableid'
    ,height: 300
    ,page: true
    ,done: function (res, curr, count) {
        //明细数据信息,默认展示第一条主表对应的明细数据
        if(dataList.length > 0 && res.data[0].detailList.length > 0){
            //默认显示第一条
            detailList = res.data[0].detailList;
        }
        table.render({
            elem: '#childinformation'
            ,data:detailList
            ,cols: [[
                {field: 'invoiceNumber',  title: '发票编号',sort:true},
                {field: 'contractNo',  title: '合同编号',sort:true},
                {field: 'splitAmount',  title: '拆分金额',edit:'text'},
                {field: 'amountClaimed', title:'认领金额',sort:true,width: 120},
                {field: 'unallocatedAmount', title:'未分摊金额',sort:true,width: 120},
                {field: 'invoiceRemainingUncollected', title:'发票未收金额',sort:true,width: 130},
                {field: 'foreignBankDeductions',  title: '国外银行扣费'},
                {field: 'domesticBankCharge',  title: '国内银行扣费'},
                {field: 'totalContract',  title: '合同总额',sort:true},
                {field: 'claimCustomer',  title: '认领客户', sort:true},
                {field: 'claimSalesman',  title: '认领业务员', sort:true},
                {field:'memo', title:'备注'},
                 {fixed: 'right', align: 'center', toolbar: '#childinformationeditor', title: '操作'}
            ]]
            ,id: 'childinformationtableid'
            ,page: true
            ,height: 300
        });
    }
});

//单击行事件
table.on('row(mainstable)', function (obj) {
    //获取当前选中的行tempId
    let tempId = obj.data.tempId;
    for(let i in dataList){
        if(tempId == dataList[i].tempId){
            table.reload('childinformationtableid', {data : dataList[i].detailList});
        }
    }
});

table.on('tool(childinformationtable)', function (obj) {
    if (obj.event === 'del') {
        layer.confirm('确认删除？',confirmInfo(3, 6), function (index) {
            //获取结汇id
            let billId = obj.data.billId;
            //获取主表id
            let parentId = obj.data.parentId;
            let temp = dataList;
            for(let i in temp){
                if(parentId == temp[i].id){
                    for(let j in temp[i].detailList){
                        if(billId == temp[i].detailList[j].billId){
                            temp[i].detailList.splice(j, 1);
                            dataList = temp;
                            layer.msg("删除成功", {icon: 6});
                            table.reload('childinformationtableid', {data : temp[i].detailList});
                            layer.close(index);
                            break;
                        }
                    }
                }
            }
        });
    }
});

table.on('edit(childinformationtable)',function (obj) {
    let old=$(this).prev().text();//旧值
    //判断数据类型 ,,,,,,,
    if((obj.field== "splitAmount" || obj.field== "foreignBankDeductions"|| obj.field== "domesticBankCharge")&&!isNumber(obj.value)) {
        layer.msg('请输入数字');
        $(this).val(old);
        return;
    }
    if(obj.field == "splitAmount"){
        //拆分金额
        let splitAmount = obj.value;
        //拆分数据
        let splitData = table.cache["childinformationtableid"];
        //获取结汇id
        let billId = obj.data.billId;
        //拆分合计
        let splitSum = 0;
        for(let i in splitData){
            if(splitData[i]["billId"] === billId){
                continue;
            }
            let deSplitAmount = splitData[i]["splitAmount"];
            splitSum = new BigNumber(splitSum).plus(deSplitAmount);
        }
        let resSplitSum = new BigNumber(splitSum).plus(splitAmount).toString();
        if(resSplitSum > obj.data["unallocatedAmount"]){
            layer.msg('拆分金额不能超过未分摊金额');
            $(this).val(old);
            return;
        }
        if(splitAmount > obj.data["invoiceRemainingUncollected"]){
            layer.msg('拆分金额不能超过发票未收金额');
            $(this).val(old);
            return;
        }
        //获取主表id
        let parentId = obj.data.parentId;
        let temp = dataList;
        for(let i in temp){
            if(parentId == temp[i].id){
                for(let j in temp[i].detailList){
                    if(billId == temp[i].detailList[j].billId){
                        temp[i].detailList[j]["splitAmount"] = splitAmount;
                        dataList = temp;
                        table.reload('childinformationtableid', {data : temp[i].detailList});
                        break;
                    }
                }
            }
        }
    }
});

$("#akeybreakup").on("click",function () {
    //向后台组装数据
    let reqList = dataList;
    let datas = JSON.stringify(reqList);
    $.ajax({
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data:datas,
        url:"receivePayment/addSplitInfo",
        success:function(res){
            if(res.status == 200){
                layer.msg("一键拆分成功", {icon: 6});
                setTimeout(function () {
                    //保存成功则关闭此页面
                    let index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                },1000)
            }else {
                layer.msg(res.msg, {icon: 5});
            }
            return false;
        }
    });
})

$("#choose").on("click",function () {
    //向后台组装数据
    let reqList = dataList;
    let datas = JSON.stringify(reqList);
    $.ajax({
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data:datas,
        url:"receivePayment/saveSplitInfo",
        success:function(res){
            if(res.status == 200){
                //执行接口
                layer.msg("保存成功", {icon: 6});
                parent.table.reload('maininformationtableid');
                setTimeout(function () {
                    //保存成功则关闭此页面
                    let index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                },1000)
            }else {
                layer.msg(res.msg, {icon: 5});
            }
            return false;
        }
    });

})

$("#shutdown").on("click",function () {
    let index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
});

function isNumber(val) {
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if (regPos.test(val) || regNeg.test(val)) {
        return true;
    } else {
        return false;
    }
}

//提示信息渲染
function confirmInfo(icon, anim) {
    let data = {
        icon: icon,
        title: "提示",
        offset: "auto",
        skin: 'layui-layer-molv',
        anim: anim
    }
    return data;
}

//生成临时id
function GenNonDuplicateID(randomLength){
    return Number(Math.random().toString().substr(3,randomLength) + Date.now()).toString(36)
}